package io.xxx.eve.task;

import com.imadcn.framework.idworker.generator.IdGenerator;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class TaskService {

    @Autowired
    private IdGenerator idGenerator;

    @Autowired
    private TaskRepository taskRepository;

    @Autowired
    private Scheduler scheduler;

    public Long create(Task task) throws SchedulerException {
        long id = idGenerator.nextId();
        task.setId(id);
        taskRepository.save(task);

        JobDetail jobDetail = JobBuilder.newJob()
                .withIdentity(task.getExecutionMode().name() + id, "task")
                .withDescription(task.getName())
                .usingJobData("taskId", id)
                .build();
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(task.getExecutionMode().name() + id, "task")
                .withDescription(task.getName())
                .build();
        scheduler.scheduleJob(jobDetail, trigger);
        return id;
    }
}
